<template>
    <div class="moments-manage">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <el-form :inline="true" :model="searchForm" class="form-inline">
                <el-form-item label="内容">
                    <el-input v-model="searchForm.content" placeholder="搜索说说内容" clearable />
                </el-form-item>
                <el-form-item label="地点">
                    <el-input v-model="searchForm.location" placeholder="搜索地点" clearable />
                </el-form-item>
                <el-form-item label="时间">
                    <el-date-picker
                        v-model="searchForm.dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作栏 -->
        <div class="operation-bar">
            <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>发布说说
            </el-button>
            <el-button type="danger" :disabled="!selectedMoments.length" @click="handleBatchDelete">
                <el-icon><Delete /></el-icon>批量删除
            </el-button>
        </div>

        <!-- 表格 -->
        <el-table
            v-loading="loading"
            :data="momentsList"
            @selection-change="handleSelectionChange"
            style="width: 100%"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="content" label="内容" show-overflow-tooltip>
                <template #default="{ row }">
                    <div class="content-cell">
                        <span>{{ row.content }}</span>
                        <div v-if="row.images?.length" class="image-previews">
                            <el-image
                                v-for="(img, index) in row.images"
                                :key="index"
                                :src="img"
                                :preview-src-list="row.images"
                                preview-teleported
                                fit="cover"
                                class="preview-image"
                            />
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />
            <el-table-column prop="likes" label="点赞数" width="100" align="center" />
            <el-table-column prop="comments" label="评论数" width="100" align="center">
                <template #default="{ row }">
                    <el-tag 
                        :type="row.comments?.length ? 'success' : 'info'" 
                        effect="light" 
                        round
                    >
                        {{ row.comments?.length || 0 }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="180" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ formatTime(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="primary" @click="handleViewComments(row)">查看评论</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 编辑/新增弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '发布说说' : '编辑说说'"
            width="600px"
        >
            <el-form :model="momentForm" label-width="80px">
                <el-form-item label="内容">
                    <el-input
                        v-model="momentForm.content"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入说说内容"
                    />
                </el-form-item>
                <el-form-item label="地点">
                    <el-input v-model="momentForm.location" placeholder="请输入地点" />
                </el-form-item>
                <el-form-item label="图片">
                    <el-upload
                        v-model:file-list="uploadFileList"
                        action="http://cylyxsz.w1.luyouxia.net/upload/images"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        multiple
                    >
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitMoment">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 评论查看弹窗 -->
        <el-dialog v-model="commentsVisible" title="评论列表" width="800px">
            <div class="comments-list">
                <div v-for="comment in commentsList" :key="comment.id" class="comment-item">
                    <div class="comment-main">
                        <div class="comment-header">
                            <span class="device-name">{{ comment.deviceName }}</span>
                            <el-tooltip :content="comment.deviceInfo">
                                <span class="device-info">{{ JSON.parse(comment.deviceInfo).device }}</span>
                            </el-tooltip>
                            <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
                        </div>
                        <div class="comment-content">{{ comment.content }}</div>
                        <div class="comment-actions">
                            <el-button link type="primary" @click="handleReply(comment)">回复</el-button>
                            <el-button link type="danger" @click="handleDeleteComment(comment)">删除</el-button>
                        </div>
                    </div>
                    
                    <!-- 回复列表 -->
                    <div v-if="comment.replies?.length" class="replies-list">
                        <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                            <div class="reply-header">
                                <span class="device-name">{{ reply.deviceName }}</span>
                                <el-tooltip :content="reply.deviceInfo">
                                    <span class="device-info">{{ JSON.parse(reply.deviceInfo).device }}</span>
                                </el-tooltip>
                                <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                            </div>
                            <div class="reply-content">{{ reply.content }}</div>
                            <div class="reply-actions">
                                <el-button link type="danger" @click="handleDeleteComment(reply, comment.id)">删除</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 添加回复弹窗 -->
        <el-dialog v-model="replyDialogVisible" title="回复评论" width="500px">
            <el-form :model="replyForm">
                <el-form-item label="回复内容">
                    <el-input 
                        v-model="replyForm.content" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入回复内容"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="replyDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitReply">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Printer } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import type { UploadFile } from 'element-plus'
import momentsApi from '@/http/apis/moments'
import axios from 'axios'

// 搜索表单
const searchForm = ref({
    content: '',
    location: '',
    dateRange: [] as string[]
})

// 说说列表项接口
interface Moment {
    id: number
    content: string
    images: string[]
    deviceName: string
    deviceInfo: string
    avatar: string
    createTime: string
    likes: number
    isLiked: boolean
    location?: string
    comments: Array<{
        id: number
        deviceName: string
        deviceInfo: string
        content: string
        createTime: string
        replies?: Reply[]
    }>
}

// 表格数据
const loading = ref(false)
const momentsList = ref<Moment[]>([])
const selectedMoments = ref<Moment[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const commentsVisible = ref(false)
const commentsList = ref<Comment[]>([])

// 表单数据
const momentForm = ref<{
    id: string | number
    content: string
    location: string
    images: UploadFile[]
}>({
    id: '',
    content: '',
    location: '',
    images: []
})

// 格式化时间
const formatTime = (time: string) => {
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 搜索相关方法
const handleSearch = () => {
    currentPage.value = 1
    fetchMomentsList()
}

const resetSearch = () => {
    searchForm.value = {
        content: '',
        location: '',
        dateRange: []
    }
    handleSearch()
}

// 表格操作方法
const handleSelectionChange = (val: any[]) => {
    selectedMoments.value = val
}

const handleAdd = () => {
    dialogType.value = 'add'
    momentForm.value = {
        id: '',
        content: '',
        location: '江苏南京',
        images: []
    }
    dialogVisible.value = true
}

const handleEdit = (row: any) => {
    dialogType.value = 'edit'
    momentForm.value = {
        id: row.id,
        content: row.content,
        location: row.location,
        images: []
    }
    existingImages.value = row.images || []
    dialogVisible.value = true
}

const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除这条说说吗？', '提示', {
            type: 'warning'
        })
        await momentsApi.deleteMoment(row.id)
        ElMessage.success('删除成功')
        fetchMomentsList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedMoments.value.length} 条说说吗？`,
            '提示',
            { type: 'warning' }
        )
        const ids = selectedMoments.value.map(item => item.id)
        await momentsApi.batchDeleteMoments(ids)
        ElMessage.success('批量删除成功')
        fetchMomentsList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
        }
    }
}

// 图片上传相关方法
const handlePictureCardPreview = (file: UploadFile) => {
    // TODO: 实现图片预览
}

const handleRemove = (file: UploadFile) => {
    if (dialogType.value === 'edit') {
        const url = file.url
        if (url) {
            const index = existingImages.value.indexOf(url)
            if (index !== -1) {
                existingImages.value.splice(index, 1)
            }
        }
    } else {
        const index = momentForm.value.images.indexOf(file)
        if (index !== -1) {
            momentForm.value.images.splice(index, 1)
        }
    }
}

// 评论相关方法
const handleViewComments = (row: Moment) => {
    commentsList.value = (row.comments || []).map(comment => ({
        ...comment,
        momentId: row.id,
        replies: (comment.replies || []).map(reply => ({
            ...reply,
            momentId: row.id
        }))
    }))
    commentsVisible.value = true
}

const handleDeleteComment = async (comment: Comment, parentId?: number) => {
    try {
        if (!comment.momentId) {
            ElMessage.error('评论数据错误')
            return
        }

        const message = parentId ? '确定要删除这条回复吗？' : '确定要删除这条评论吗？'
        await ElMessageBox.confirm(message, '提示', {
            type: 'warning'
        })
        
        await momentsApi.deleteComment(comment.momentId, comment.id)
        ElMessage.success(parentId ? '删除回复成功' : '删除评论成功')
        
        // 更新评论列表
        const currentMoment = momentsList.value.find(
            moment => moment.id === comment.momentId
        )
        if (currentMoment) {
            handleViewComments(currentMoment)
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除错误:', error)
        }
    }
}

// 提交表单
const submitMoment = async () => {
    try {
        const allImages = dialogType.value === 'edit' 
            ? existingImages.value  // 编辑模式使用existingImages
            : momentForm.value.images.map(file => file.url).filter((url): url is string => url !== undefined)

        const formData: MomentForm = {
            content: momentForm.value.content,
            location: momentForm.value.location,
            images: allImages,
            userId: 1
        }
        
        if (dialogType.value === 'add') {
            await momentsApi.addMoment(formData)
        } else {
            await momentsApi.updateMoment(momentForm.value.id, formData)
        }
        
        ElMessage.success(dialogType.value === 'add' ? '发布成功' : '编辑成功')
        dialogVisible.value = false
        existingImages.value = []
        momentForm.value.images = []
        fetchMomentsList()
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 分页方法
const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchMomentsList()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchMomentsList()
}

// 获取说说列表
const fetchMomentsList = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            content: searchForm.value.content,
            location: searchForm.value.location,
            startDate: searchForm.value.dateRange[0],
            endDate: searchForm.value.dateRange[1]
        }
        const response = await momentsApi.getMoments(params)
        momentsList.value = response.list
        total.value = response.total
        loading.value = false
    } catch (error) {
        loading.value = false
        ElMessage.error('获取说说列表失败')
    }
}

onMounted(() => {
    fetchMomentsList()
})

// First, let's add the required interfaces at the top of the script section
interface MomentQuery {
    pageNum?: number
    pageSize?: number
    content?: string
    location?: string
    startDate?: string
    endDate?: string
    momentId?: number // Add this for single moment queries
}

interface MomentForm {
    content: string
    location: string
    images: string[]
    userId: number
}

// Add this interface for the upload response
interface UploadResponse {
    code: string
    data: string[]
}

interface Comment {
    id: number
    momentId: number | string
    deviceName: string
    deviceInfo: string
    content: string
    createTime: string
    replies?: Reply[]
}

interface Reply {
    id: number
    content: string
    createTime: string
}

interface UploadFile {
    name: string
    percentage?: number
    status: 'ready' | 'uploading' | 'success' | 'fail'
    size?: number
    response?: unknown
    uid: number
    url?: string
    raw?: File
}

const handleUpload = async (file: File) => {
    try {
        const formData = new FormData()
        formData.append('file', file)

        const response = await momentsApi.uploadImage(formData)
        
        if (response.code === '0') {
            const serverImageUrl = response.data[0]
            const newUploadFile: UploadFile = {
                name: file.name,
                status: 'success',
                url: serverImageUrl,
                uid: Date.now()
            }
            
            if (dialogType.value === 'edit') {
                existingImages.value.push(serverImageUrl)
            } else {
                momentForm.value.images.push(newUploadFile)
            }
        }
    } catch (error) {
        ElMessage.error('图片上传失败')
    }
}

// 在 script setup 中添加新的状态管理
const newImageFiles = ref<File[]>([])  // 存储新上传的文件
const existingImages = ref<string[]>([])  // 存储已有的图片URL

// 在 script setup 中添加计算属性
const uploadFileList = computed({
    get: () => {
        if (dialogType.value === 'edit') {
            return existingImages.value.map((url, index) => ({
                name: `image-${index}`,
                status: 'success' as const,
                url,
                uid: index
            }))
        }
        return momentForm.value.images
    },
    set: (val: UploadFile[]) => {
        if (dialogType.value === 'edit') {
            existingImages.value = val.map(file => file.url).filter((url): url is string => !!url)
        } else {
            momentForm.value.images = val
        }
    }
})

// 在 script setup 中添加打印相关的方法
const printComments = (comments: any[]) => {
    // 创建打印内容
    const printContent = comments.map(comment => `
        设备：${comment.deviceName}
        设备信息：${comment.deviceInfo}
        评论内容：${comment.content}
        评论时间：${formatTime(comment.createTime)}
        ----------------------------------------
    `).join('\n')

    // 创建打印窗口
    const printWindow = window.open('', '_blank')
    if (!printWindow) {
        ElMessage.warning('请允许打开新窗口')
        return
    }

    // 设置打印窗口的内容
    printWindow.document.write(`
        <html>
            <head>
                <title>评论列表</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        padding: 20px;
                        white-space: pre-wrap;
                    }
                </style>
            </head>
            <body>
                <h2>评论列表</h2>
                ${printContent}
            </body>
        </html>
    `)

    printWindow.document.close()
    printWindow.print()
    printWindow.close()
}

// 添加回复相关的响应式数据
const replyDialogVisible = ref(false)
const replyForm = ref({
    content: '',
    commentId: 0,
    momentId: 0,
    deviceName: 'admin',
    isAdmin: true
})

// 添加回复相关的方法
const handleReply = (comment: Comment) => {
    if (!comment.momentId) {
        ElMessage.error('评论数据错误')
        return
    }
    
    selectedComment.value = comment
    replyForm.value = {
        content: '',
        commentId: comment.id,
        momentId: comment.momentId,
        deviceName: 'admin',
        isAdmin: true
    }
    replyDialogVisible.value = true
}

const submitReply = async () => {
    try {
        if (!replyForm.value.content.trim()) {
            ElMessage.warning('请输入回复内容')
            return
        }

        await momentsApi.addReply(
            replyForm.value.momentId,
            replyForm.value.commentId,
            {
                content: replyForm.value.content,
                deviceName: replyForm.value.deviceName,
                isAdmin: replyForm.value.isAdmin
            }
        )

        ElMessage.success('回复成功')
        replyDialogVisible.value = false

        // 刷新评论列表
        const currentMoment = momentsList.value.find(
            moment => moment.comments?.some(c => c.id === replyForm.value.commentId)
        )
        if (currentMoment) {
            handleViewComments(currentMoment)
        }
    } catch (error) {
        console.error('回复评论错误:', error)
    }
}

const handleDeleteReply = async (commentId: number, replyId: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这条回复吗？', '提示', {
            type: 'warning'
        })
        
        const response = await momentsApi.deleteReply(commentId, replyId)
        
        if (response.code === '0') {
            ElMessage.success('删除回复成功')
            // 刷新评论列表
            const currentMoment = momentsList.value.find(
                moment => moment.comments?.some(c => c.id === commentId)
            )
            if (currentMoment) {
                handleViewComments(currentMoment)
            }
        } else {
            ElMessage.error(response.message || '删除回复失败')
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            console.error('删除回复错误:', error)
            ElMessage.error(error?.message || '删除回复失败，请稍后重试')
        }
    }
}

// 添加选中的评论状态
const selectedComment = ref<Comment | null>(null)
</script>

<style scoped>
.moments-manage {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.search-bar {
    margin-bottom: 20px;
}

.operation-bar {
    margin-bottom: 20px;
}

.content-cell {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.image-previews {
    display: flex;
    gap: 8px;
}

.preview-image {
    width: 50px;
    height: 50px;
    border-radius: 4px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-upload--picture-card) {
    --el-upload-picture-card-size: 100px;
}

/* 添加评论相关样式 */
.comment-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.reply-list {
    margin-left: 20px;
    padding-left: 10px;
    border-left: 2px solid var(--el-border-color-lighter);
}

.reply-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 4px 0;
    color: var(--el-text-color-regular);
    font-size: 13px;
}

.reply-info {
    color: var(--el-text-color-secondary);
}

/* 添加回复区域样式 */
.reply-section {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
}

.reply-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 16px;
}

.reply-header h4 {
    margin: 0;
    color: var(--el-text-color-primary);
}

.reply-to {
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

/* 替换评论相关样式 */
.comments-list {
    padding: 0 16px;
}

.comment-item {
    margin-bottom: 24px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    padding-bottom: 16px;
}

.comment-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
}

.comment-main {
    margin-bottom: 12px;
}

.comment-header, .reply-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.device-name {
    font-weight: 500;
    color: var(--el-text-color-primary);
}

.device-info {
    cursor: help;
}

.comment-time, .reply-time {
    margin-left: auto;
    font-size: 13px;
}

.comment-content, .reply-content {
    margin-bottom: 8px;
    line-height: 1.6;
    color: var(--el-text-color-primary);
}

.comment-actions, .reply-actions {
    display: flex;
    gap: 12px;
}

.replies-list {
    margin-left: 24px;
    padding-left: 16px;
    border-left: 2px solid var(--el-border-color-lighter);
}

.reply-item {
    margin-bottom: 16px;
    padding: 12px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
}

.reply-item:last-child {
    margin-bottom: 0;
}
</style>
